package com.ygxsk.carhome.retrofit;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ObjectUtils;
import com.ygxsk.carhome.constant.ConstantSign;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import okio.BufferedSource;
import okio.Okio;
import retrofit2.Converter;

public class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Type type;

    public FastJsonResponseBodyConverter(Type type) {
        this.type = type;
    }

    /*
     * 转换方法
     */
    @Override
    public T convert(ResponseBody value) throws IOException {

        try {

            BufferedSource bufferedSource = Okio.buffer(value.source());
            String tempStr = bufferedSource.readUtf8();
            bufferedSource.close();
            //LogUtils.d(ConstantApi.LOGCAT_NOMAL + "响应的数据是->" + tempStr);
            //itchen->响应的数据是->{"data":"","message":"无数据","code":"20002"}

            return JSON.parseObject(tempStr, type);

        } catch (Exception e) {

            if (!ObjectUtils.isEmpty(e)) {
                //LogUtils.d(ConstantApi.LOGCAT_NOMAL + "json-convert-响应异常->" + e.getLocalizedMessage());
                new ApiRequestSubListener<T>() {
                }.addLogInApiRequestListener(null,//
                        ApiService.addLogUrl,//
                        ConstantSign.REQUEST_METHOD_POST,//
                        null,//
                        e.getLocalizedMessage().toString());//
            } else {
                new ApiRequestSubListener<T>() {
                }.addLogInApiRequestListener(null,//
                        ApiService.addLogUrl,//
                        ConstantSign.REQUEST_METHOD_POST,//
                        null,//
                        "FastJsonResponseBodyConverter转换响应异常");//
            }

            throw new IOException("JSON parse error: " + e.getMessage(), e);

        } finally {
            value.close();
        }

    }

    //fastjson的源码
//    public T convert(ResponseBody value) throws IOException {
//        try {
//            return JSON.parseObject(value.bytes()
//                    , fastJsonConfig.getCharset()
//                    , type
//                    , fastJsonConfig.getParserConfig()
//                    , fastJsonConfig.getParseProcess()
//                    , JSON.DEFAULT_PARSER_FEATURE
//                    , fastJsonConfig.getFeatures()
//            );
//        } catch (Exception e) {
//            throw new IOException("JSON parse error: " + e.getMessage(), e);
//        } finally {
//            value.close();
//        }
//    }

//    input,
//    clazz,
//    ParserConfig.global,
//    DEFAULT_PARSER_FEATURE,
//    features

}
